package com.uduemc.biso.node.web.api.service.impl;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.entities.publishdata.DataBody;
import com.uduemc.biso.node.core.common.feign.CPublishFeign;
import com.uduemc.biso.node.core.operate.entities.OperateLog;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.dto.RequestActionPublishSaveOperateLog;
import com.uduemc.biso.node.web.api.service.PublishService;
import com.uduemc.biso.node.web.api.service.WebSiteService;
import com.uduemc.biso.node.web.service.OperateLoggerService;
import com.uduemc.biso.node.web.utils.IpUtil;

import cn.hutool.core.collection.CollectionUtil;

@Service
public class PublishServiceImpl implements PublishService {

	@Autowired
	private CPublishFeign cPublishFeign;

	@Autowired
	private WebSiteService webSiteServiceImpl;

	@Autowired
	private OperateLoggerService operateLoggerServiceImpl;

	@Autowired
	private RequestHolder requestHolder;

	@Override
	public boolean save(DataBody dataBody, List<RequestActionPublishSaveOperateLog> operateLog)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		RestResult restResult = cPublishFeign.save(dataBody);
		Integer data = RestResultUtil.data(restResult, Integer.class);
		boolean bool = (data != null && data.intValue() == 1);
		if (bool) {
			// 清理页面内容缓存
			webSiteServiceImpl.cacheCurrentSiteClear();

			// 写入操作日志
			if (CollectionUtil.isNotEmpty(operateLog)) {
				for (RequestActionPublishSaveOperateLog requestActionPublishSaveOperateLog : operateLog) {
					OperateLog log = new OperateLog();
					log.setHostId(requestHolder.getHost().getId()).setSiteId(requestHolder.getCurrentSite().getId())
							.setLanguageId(requestHolder.getCurrentSite().getLanguageId());
					log.setUserId(requestHolder.getUserId()).setUserType(requestHolder.getUsertype()).setUsername(requestHolder.getUsername());
					log.setModelName(requestActionPublishSaveOperateLog.getModelName()).setModelAction(requestActionPublishSaveOperateLog.getModelAction())
							.setContent(requestActionPublishSaveOperateLog.getContent());
					log.setStatus((short) 1).setIpaddress(IpUtil.getIpAddr(requestHolder.getCurrentRequest()));
					log.setParam("").setReturnValue("").setOperateItem("");
					operateLoggerServiceImpl.insert(log);
				}
			}
		}
		return bool;
	}

}
